package com.org.platform.utils.async;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.function.Function;

/**
 * @author duheng
 * @Date 2021/3/16 16:26
 */
public class CompletableFutureTest {

	public static void main(String[] args) {
		int a = 0;
		CompletableFuture<Void> futurea = CompletableFuture.runAsync(() -> {
			System.out.println("AA" + a);
		}).thenAccept(new Consumer<Void>() {
			@Override
			public void accept(Void aVoid) {
				System.out.println("BB");
			}
		}).whenComplete(new BiConsumer<Void, Throwable>() {
			@Override
			public void accept(Void aVoid, Throwable throwable) {
				System.out.println("CC");
			}
		}).exceptionally(new Function<Throwable, Void>() {
			@Override
			public Void apply(Throwable throwable) {
				System.out.println("DD" + throwable);
				return null;
			}
		});

		try {
			futurea.get();
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (ExecutionException e) {
			e.printStackTrace();
		}

		CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
			try {
				TimeUnit.SECONDS.sleep(1);
			} catch (InterruptedException e) {
			}
			return "123";
		}).thenApply(new Function<String, String>() {
			@Override
			public String apply(String s) {
				return "456" + s;
			}
		}).whenComplete(new BiConsumer<String, Throwable>() {
			@Override
			public void accept(String s, Throwable throwable) {
				System.out.println("finished it");
			}
		}).exceptionally(new Function<Throwable, String>() {
			@Override
			public String apply(Throwable throwable) {
				return "出错了";
			}
		});
		try {
			String ss = future.get(5, TimeUnit.SECONDS);
			System.out.println(ss);
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (ExecutionException e) {
			e.printStackTrace();
		} catch (TimeoutException e) {
			e.printStackTrace();
		}
	}

}
